package com.iteaj.demo.server.protocol;

import com.iteaj.demo.server.ServerDemoMessage;
import com.iteaj.demo.server.ServerProtocolType;
import com.iteaj.network.AbstractMessage;
import com.iteaj.network.Message;
import com.iteaj.network.server.protocol.DeviceRequestProtocol;
import com.iteaj.network.utils.ByteUtil;

import java.nio.charset.StandardCharsets;

/**
 * 客户端请求平台示例
 */
public class ClientRequestPlatformDemoProtocol extends DeviceRequestProtocol<ServerDemoMessage> {

    /**
     * 请求内容
     */
    private String reqContent;

    /**
     * 响应内容
     */
    private String respContent;

    public ClientRequestPlatformDemoProtocol(ServerDemoMessage requestMessage) {
        super(requestMessage);
    }

    /**
     * 构建响应给客户端的报文
     * @return
     */
    @Override
    protected ServerDemoMessage doBuildResponseMessage() {
        final Message.MessageHead head = requestMessage.getHead();

        final byte[] deviceMsg = ByteUtil.hexToByte(head.getEquipCode());
        final byte[] typeMsg = ByteUtil.hexToByte(protocolType().getCode());
        final byte[] messageMsg = ByteUtil.hexToByte(head.getMessageId());

        final byte[] contentBytes = ByteUtil.hexToByte(this.respContent);
        final byte[] byteMessage = new byte[11 + contentBytes.length];

        ByteUtil.addBytes(byteMessage, deviceMsg, 0);
        ByteUtil.addBytes(byteMessage, typeMsg, 3);
        ByteUtil.addBytes(byteMessage, messageMsg, 4);
        ByteUtil.addBytes(byteMessage, contentBytes, 11);

        final ServerDemoMessage message = new ServerDemoMessage(head, AbstractMessage.VOID_MESSAGE_BODY);

        message.setMessage(byteMessage);
        return message;
    }

    /**
     * 解析客户端请求的设备报文
     * @param requestMessage
     */
    @Override
    protected void resolverRequestMessage(ServerDemoMessage requestMessage) {
        final byte[] message = requestMessage.getMessage();
        final String msg = ByteUtil.bytesToHex(message);

        this.reqContent = msg.substring(22);
    }

    @Override
    public ServerProtocolType protocolType() {
        return ServerProtocolType.ClientRequest;
    }

    public String getRespContent() {
        return respContent;
    }

    public void setRespContent(String respContent) {
        this.respContent = respContent;
    }

    public String getReqContent() {
        return reqContent;
    }

    public void setReqContent(String reqContent) {
        this.reqContent = reqContent;
    }
}
